﻿using NHibernate;
using NLog;
using Susha.Areas.Admin.Models.Requests;
using Susha.Models.Pages;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Susha.Models.Helpers
{
    public static class SushiRepository
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();

        public static Sushi Save(Sushi sushi)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    if (String.IsNullOrWhiteSpace(sushi.SmallPhoto))
                        sushi.SmallPhoto = "default.jpg";

                    session.SaveOrUpdate(sushi);
                    transaction.Commit();

                    _logger.Info(String.Format("Sushi {0} was created by {1};", 
                                                    sushi.Name, 
                                                    HttpContext.Current.User.Identity.Name));
                    return sushi;
                }
            }
        }

        public static IList<Sushi> GetSushiByCategory(Category category)
        {
            return GetSushiByCategory(category.Id);
        }

        public static IList<Sushi> GetSushiByCategory(Int32 categoryId)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                return
                    session.QueryOver<Sushi>().Where(x => x.ParentCategory.Id == categoryId).List<Sushi>()
                    ?? new List<Sushi>();
            }
        }

        public static Sushi GetSushiById(Int32 id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Sushi sushi = session.QueryOver<Sushi>().Where(x => x.Id == id).SingleOrDefault();
                if (sushi == null)
                {
                    _logger.Error(String.Format("SushiRepository.GetSushiById({0}): value is empty", id));
                }
                return sushi;
            }
        }

        public static Boolean ChangePrice(Int32 id, Int32 newPrice)
        {
            Boolean result = false;
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Sushi sushi = session.QueryOver<Sushi>().Where(x => x.Id == id).SingleOrDefault();
                if (sushi != null)
                {
                    Int32 oldPrice = sushi.Price; 
                    sushi.Price = newPrice;
                    using (ITransaction tranaction = session.BeginTransaction())
                    {
                        session.SaveOrUpdate(sushi);
                        tranaction.Commit();

                        _logger.Info("Price for {0} was changed {1} = {2} by {3}", 
                                        sushi.Name, 
                                        oldPrice, 
                                        sushi.Price, 
                                        HttpContext.Current.User.Identity.Name);
                        result = true;
                    }
                }
            }
            return result;
        }

        public static Boolean ChangeSushiName(Int32 id, String newName)
        {
            Boolean result = false;
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Sushi sushi = session.QueryOver<Sushi>().Where(x => x.Id == id).SingleOrDefault();
                if (sushi != null)
                {
                    String oldName = sushi.Name;
                    sushi.Name = newName;

                    using (ITransaction tranaction = session.BeginTransaction())
                    {
                        session.SaveOrUpdate(sushi);
                        tranaction.Commit();

                        _logger.Info("Sushi name was changed {0} => {1} by {2}", 
                                        oldName, 
                                        sushi.Name, 
                                        HttpContext.Current.User.Identity.Name);
                        result = true;
                    }
                }
            }
            return result;
        }

        public static String DeleteSushi(Int32 sushiId)
        {
            String resultError = String.Empty;
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Sushi sushi = session.QueryOver<Sushi>().Where(x => x.Id == sushiId).SingleOrDefault<Sushi>();
                if (sushi != null)
                {
                    try
                    {
                        using (ITransaction transaction = session.BeginTransaction())
                        {
                            session.Delete(sushi);
                            CommonRepository.DeletePhoto(sushi.SmallPhoto);
                            transaction.Commit();
                        }
                    }
                    catch (Exception e)
                    {
                        resultError = e.Message;
                    }
                }
                else
                {
                    resultError = "Не могу найти суши";
                }
            }

            return resultError;
        }

        public static String DeleteSushi(Sushi sushi)
        {
            return DeleteSushi(sushi.Id);
        }

        public static void ChangePhoto(Int32 sushiId, String newPhoto)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Sushi sushi = session.QueryOver<Sushi>().Where(x => x.Id == sushiId).SingleOrDefault<Sushi>();
                if (sushi != null)
                {
                    String oldPhoto = sushi.SmallPhoto;
                    sushi.SmallPhoto = newPhoto;
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        session.Update(sushi);
                        //The reason of placing Delete-method here is that "sushi" should be updated first
                        //    and after that we can delete our old photo
                        CommonRepository.DeletePhoto(oldPhoto);
                        transaction.Commit();
                    }
                }
            }
        }
    }
}